import React, { Component, ComponentClass } from 'react';
import {AtCountdown, AtIcon} from "taro-ui";
import Taro from '@tarojs/taro';
import {View, Block, Image, Text} from '@tarojs/components'
import {GetRequest, vcmonitor} from "../utils/tools";
import {newHttp} from "../utils/request";
import {
  NEW_GET_WXGLOD_ORDER_DETAIL,
  ACTIVITY_GROUP_ACTIVITY_INFO,
  TARO_ENV,
  ACTIVITY_GROUP_BUY_DETAIL
} from "../constants/api";
import {http} from "../utils/http";
import './index.scss'

type PageOwnProps = {}

type PageState = {}

class PayRoot extends Component {
  state: {
    outTradeNo: string | undefined
    orderInfo: any
    groupInfo: any
    userList: any
  } = {
    outTradeNo: '',
    orderInfo: {},
    groupInfo: {},
    userList: []
  }

  async UNSAFE_componentWillMount() {
    vcmonitor(this)
    let mchData = {}
    const {out_trade_no} = Taro.getCurrentInstance().router.params
    let orderInfo = await newHttp.catchGet(NEW_GET_WXGLOD_ORDER_DETAIL + '/' + out_trade_no+'?d='+new Date())
    //最多100次
    let times = 100;
    let bol = false;
    //如果是204状态
    if (orderInfo && orderInfo === 204) {
      bol = true;
    }
    while (bol) {
      if (times <= 0) {
        break;
      }
      times = times - 1;
      orderInfo = await newHttp.catchGet(NEW_GET_WXGLOD_ORDER_DETAIL + '/' + out_trade_no+'?d='+new Date())
      bol = !!(orderInfo && orderInfo === 204);
    }
    let mpkey = ''
    if (orderInfo && orderInfo.mpkey) {
      mpkey = orderInfo.mpkey
    } else {
      const user = Taro.getStorageSync('user') || ''
      if (user && user.mpkey){
        mpkey = user.mpkey
      }
    }
    if (!orderInfo) {
      setTimeout(() => {
        document.getElementById('jumpHome').onclick = function () {
          mchData = {
            action: 'jumpOut',
            jumpOutUrl: window.location.origin + `/pages/index/index?mpkey=${mpkey}`,
          };
          window.parent.postMessage(JSON.stringify(mchData), 'https://payapp.weixin.qq.com');
        }
      }, 200)
    } else {
      setTimeout(() => {
        document.getElementById('payOtherBtn').onclick = function () {
          let _origin = window.location.origin
          _origin = _origin.replace('https','http');
          mchData = {
            action: 'jumpOut',
            jumpOutUrl: _origin + `/main/order/success?pay=${orderInfo.total_fee}&mpkey=${mpkey}`,
          };
          window.parent.postMessage(JSON.stringify(mchData), 'https://payapp.weixin.qq.com');
        }
      }, 200)
      if (orderInfo.group_activity_id) {
        const data = await http.HGet(ACTIVITY_GROUP_ACTIVITY_INFO, {order_num: orderInfo.order_num})
        const datas = await http.HGet(ACTIVITY_GROUP_BUY_DETAIL, {group_buy_id: data.data.group_buy_id})
        const joinPeople = datas.data.join_people
        const userList = []
        const len = datas.data.join_people.length
        if (len !== data.all_people_num) {
          const number = data.data.all_people_num >= 5 ? 5 : data.data.all_people_num
          for (let i = 0; i < number; i++) {
            if (i + 1 <= len) {
              userList.push(joinPeople[i])
            } else {
              userList.push({
                head_img: 'https://img.yzcdn.cn/public_files/2018/09/05/e0ff5968e453ee8811e43ac232e537a8.png',
                isPlaceholder: true
              })
            }
          }
        }
        this.setState({groupInfo: data.data, userList})
        setTimeout(() => {
          document.getElementById('inviteFriends').onclick = function () {
            let _origin = window.location.origin
            _origin = _origin.replace('https','http');
            mchData = {
              action: 'jumpOut',
              jumpOutUrl: _origin + `/common/group/detail?orderNum=${orderInfo.order_num}&category=${orderInfo.category}&itemId=${orderInfo.uuid}&showLeadModel=true&mpkey=${mpkey}`,
            };
            window.parent.postMessage(JSON.stringify(mchData), 'https://payapp.weixin.qq.com');
          }
        }, 200)
      }
    }
    this.setState({orderInfo, outTradeNo: out_trade_no})
    mchData = {
      action: 'onIframeReady',
      displayStyle: 'SHOW_CUSTOM_PAGE',
      height: 960
    };
    const postData = JSON.stringify(mchData)
    window.parent.postMessage(postData, 'https://payapp.weixin.qq.com')
  }

  render() {
    const {outTradeNo, orderInfo, groupInfo, userList} = this.state
    return (
      <View className='pay-root'>
        {outTradeNo && orderInfo ? <Block>
          {!orderInfo.group_activity_id ? <View className='h-f-pay-root'>
            <AtIcon value='icon icon-shiquan-01' size='70px' color='#4ba534' />
            <View className='pay-success'>支付成功</View>
            <View className='pay-total'>你本单总消费(元)</View>
            <View className='pay-total-money'>{orderInfo.total_fee}</View>
            {process.env.P_ENV !== 'kd' && <View className='pay-other-btn' id='payOtherBtn'>查看更多</View>}
            {process.env.P_ENV === 'kd' && <View className='pay-other-btn' id='payOtherBtn'>请您务必点击此文字识别二维码进群<br />便于日后订单使用<br />群里还有免单、红包、优惠券等福利</View>}
          </View> : <View className='detail-wrapper'>
            {groupInfo && <View className='root'>
              <View className='root__bg' />
              <View className='root-title' />
              <View className='goods-wrap'>
                <View className='good-img'><Image className='img' src={groupInfo.goods_img} mode='aspectFill' /></View>
                <View className='pro-info'>
                  <View className='pro-name'>{groupInfo.goods_name}</View>
                  <View className='price-box'>
                    <View className='price' style='color: #ff3e01'><Text className='symbol'
                      style='color: #ff3e01'
                    >￥</Text>{groupInfo.total_fee}
                    </View>
                    <View className='market_price'><Text className='price'
                      style='color:#969696;'
                    >价格</Text>
                      <View className='line-through'>
                        <Text className='symbol' style='color:#969696;'>￥</Text><Text
                          className='price'
                          style='color:#969696;'
                        >{groupInfo.goods_market_price}</Text>
                      </View>
                    </View>
                  </View>
                </View>
              </View>
            </View>}
            {groupInfo && <View className='order-detail'>
              <View>
                {groupInfo.status >= 1 &&
                <View className='group-success' style='text-align:center;'><Image mode='widthFix'
                  src='https://resource.ivcheng.com/upload/images/20210927/1632712169387_149.png'
                  className='img'
                /></View>}
                {groupInfo.status !== 1 && <View className='group-header'>
                  <View className='line' />
                  <View className='dot' />
                  <View className='title'>拼团剩余时间</View>
                  <View className='dot' />
                  <View className='line' />
                </View>}
                {groupInfo && groupInfo.status !== 1 && groupInfo.date_poor &&
                <AtCountdown isCard isShowDay format={{day: '天', hours: ':', minutes: ':', seconds: ''}} seconds={0}
                  day={JSON.parse(groupInfo.date_poor).day} hours={JSON.parse(groupInfo.date_poor).hour}
                  minutes={JSON.parse(groupInfo.date_poor).min}
                />}
                <View className='avatar-wrap'>
                  {userList.map((item, index) => <View className='avatar-wrap-item'
                    style={`z-index: ${userList.length - index}`}
                  >
                    {index <= 4 && <Block>
                      {userList.length >= 5 && index === 2 && <Text
                        className={`avatar-list-wrap-item-ellipsis ${TARO_ENV + '-avatar-list-wrap-item-ellipsis'}`}
                      >...</Text>}
                      {userList.length >= 5 && index !== 2 &&
                      <Image src={item.head_img} className={`img ${item.isPlaceholder && 'item__img--noborder'}`} />}
                      {userList.length < 5 &&
                      <Image src={item.head_img} className={`img ${item.isPlaceholder && 'item__img--noborder'}`} />}
                    </Block>}
                    {!!item.is_leader && <View className='item__tag' style={`z-index: ${userList.length}`}>团长</View>}
                  </View>)}
                </View>
                {!!groupInfo.rest_num &&
                <View className='need-num'>还差 <Text className='nums' decode>{groupInfo.rest_num}</Text>人，即可拼团成功！</View>}
              </View>
              {groupInfo.status !== -1 && <View className='btn-wrapper'>
                {!!groupInfo.rest_num &&
                <View className='invite-friends' id='inviteFriends'>邀请好友参团</View>}
              </View>}
            </View>}
          </View>}
        </Block> : <View className='h-f-pay-root'>
          <AtIcon value='icon icon-shiquan-01' size='70px' color='#4ba534' />
          <View className='pay-success'>支付成功</View>
          {process.env.P_ENV !== 'kd' && <View className='pay-other-btn' id='jumpHome'>查看更多</View>}
          {process.env.P_ENV === 'kd' && <View className='pay-other-btn' id='jumpHome'>请您务必点击此文字识别二维码进群<br />便于日后订单使用<br />群里还有免单、红包、优惠券等福利</View>}
        </View>}
      </View>
    )
  }
}

export default PayRoot as ComponentClass<PageOwnProps, PageState>
